<template>
	<view class="duty-people-container">
		<!-- 主体内容 -->
		<view class="content">
			<!-- 角色选择 -->
			<view class="role-tabs">
				<block v-for="role in roles" :key="role.key">
					<view class="role-tab" :class="{ active: selectedRole === role.key }" @click="changeRole(role.key)">
						{{ role.label }} ({{ role.count || 0 }})
					</view>
				</block>
			</view>

			<!-- 用户列表 -->
			<view class="people-list">
				<view v-if="users.length > 0" class="user-buttons">
					<block v-for="user in users" :key="user.userId">
						<button class="user-button" :class="{ active: isSelected(user.userId) }"
							@click="toggleUser(user.userId)">
							{{ user.username }}
						</button>
					</block>
				</view>
				<view v-else class="no-data">暂无用户</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-button">
				<button type="primary" :loading="loading" @click="submitDutyPeople">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loading: false,
				error: null,
				users: [],
				selectedUsers: {
					leaders: [],
					staffs: []
				},
				roles: [{
						key: 'leaders',
						label: '带班领导',
						count: 0
					},
					{
						key: 'staffs',
						label: '值班职工',
						count: 0
					}
				],
				selectedRole: 'leaders'
			};
		},

		async mounted() {
			await this.initData();
		},

		methods: {
			async initData() {
				this.loading = true;
				this.error = null;

				try {
					const [userRes, dutyRes] = await Promise.all([
						this.loadUserList(),
						this.loadDutyPeople()
					]);

					// 初始化 selectedUsers 数据，标记 isNew: false 表示已保存
					this.selectedUsers.leaders = dutyRes
						.filter(d => d.role === 'leaders')
						.map(d => ({
							userId: d.userId,
							username: d.username,
							mobile: d.mobile,
							role: d.role,
							selected: d.selected ?? true,
							isNew: false
						}));

					this.selectedUsers.staffs = dutyRes
						.filter(d => d.role === 'staffs')
						.map(d => ({
							userId: d.userId,
							username: d.username,
							mobile: d.mobile,
							role: d.role,
							selected: d.selected ?? false,
							isNew: false
						}));

					// 更新 tab 显示数量
					this.roles[0].count = this.selectedUsers.leaders.length;
					this.roles[1].count = this.selectedUsers.staffs.length;

				} catch (err) {
					this.error = '数据加载失败，请刷新重试';
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
					//console.error('初始化数据失败:', err);
				} finally {
					this.loading = false;
				}
			},

			async loadUserList() {
				const obj = uniCloud.importObject('users');
				try {
					const res = await obj.getUserInfosimple();
					if (res.code === 0 && Array.isArray(res.data)) {
						this.users = res.data.map(user => ({
							userId: user._id,
							username: user.username,
							mobile: user.mobile
						}));
					} else {
						throw new Error('用户列表数据格式错误或为空');
					}
				} catch (err) {
					//console.error('加载用户列表失败:', err);
					uni.showToast({
						title: '用户列表加载失败',
						icon: 'none'
					});
				}
			},

			async loadDutyPeople() {
				const obj = uniCloud.importObject('duty-people');
				try {
					const res = await obj.getDutyPeople();
					if (res.code === 0 && Array.isArray(res.data)) {
						return res.data;
					} else {
						throw new Error('值班数据格式错误');
					}
				} catch (err) {
					//console.error('加载值班数据失败:', err);
					return [];
				}
			},

			changeRole(roleKey) {
				if (this.selectedRole === roleKey) return;
				this.selectedRole = roleKey;
			},

			isSelected(userId) {
				const user = this.selectedUsers[this.selectedRole].find(u => u.userId === userId);
				return user ? user.selected : false;
			},

			toggleUser(userId) {
				const currentList = [...this.selectedUsers[this.selectedRole]];
				const userIndex = currentList.findIndex(u => u.userId === userId);

				if (userIndex > -1) {
					// 已存在，切换 selected 状态
					const user = currentList[userIndex];
					// 使用 Vue.set 确保 selected 属性的响应式更新
					this.$set(currentList, userIndex, {
						...user,
						selected: !user.selected
					});
				} else {
					const user = this.users.find(u => u.userId === userId);
					if (user) {
						currentList.push({
							userId: user.userId,
							username: user.username,
							mobile: user.mobile,
							role: this.selectedRole,
							selected: true,
							isNew: true // 标记为新添加
						});
					}
				}

				this.selectedUsers[this.selectedRole] = currentList;

				// 更新 tab 显示数量，仅统计 selected: true 的人数
				this.roles.find(r => r.key === 'leaders').count =
					this.selectedUsers.leaders.filter(u => u.selected).length;

				this.roles.find(r => r.key === 'staffs').count =
					this.selectedUsers.staffs.filter(u => u.selected).length;
			},

			async submitDutyPeople() {
				if (this.loading) return;

				this.loading = true;

				try {
					// 合并两个角色的所有 selected: true 的人员
					const allSelectedUsers = [
						...this.selectedUsers.leaders.filter(u => u.selected),
						...this.selectedUsers.staffs.filter(u => u.selected)
					];

					if (allSelectedUsers.length === 0) {
						uni.showToast({
							title: '请至少选择一个人员',
							icon: 'none'
						});
						this.loading = false;
						return;
					}

					// 构造提交数据，保留 isNew 字段用于区分新旧数据
					const dutyData = allSelectedUsers.map(user => ({
						userId: user.userId,
						username: user.username,
						mobile: user.mobile,
						role: user.role,
						selected: true,
						isNew: user.isNew ?? true
					}));

					// //console.log('提交数据:', dutyData);

					// 调用云函数保存
					const obj = uniCloud.importObject('duty-people');
					const res = await obj.saveDutyPeople({
						data: dutyData
					});

					if (res.code === 0) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
						setTimeout(() => uni.navigateBack(), 1000);
					} else {
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					});
					//console.error('提交值班数据失败:', err);
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style scoped>
	.duty-people-container {
		padding: 20rpx;
	}

	.role-tabs {
		display: flex;
		margin-bottom: 30rpx;
	}

	.role-tab {
		flex: 1;
		padding: 20rpx;
		text-align: center;
		border-bottom: 4rpx solid #eee;
		font-size: 28rpx;
		color: #666;
	}

	.role-tab.active {
		border-color: #007AFF;
		color: #007AFF;
		font-weight: bold;
	}

	.people-list {
		min-height: 100rpx;
	}

	.user-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.user-button {
		width: calc(25% - 15rpx);
		/* 一行4个按钮 */
		padding: 10rpx 0;
		background-color: #f0f0f0;
		color: #333;
		font-size: 24rpx;
		border-radius: 6rpx;
	}

	.user-button.active {
		background-color: #007AFF;
		color: #fff;
	}

	.no-data {
		color: #999;
		font-size: 26rpx;
		text-align: center;
		margin-top: 60rpx;
	}

	.submit-button {
		margin-top: 50rpx;
		padding: 0 40rpx;
	}
</style>